
package com.ifcar.app.view;

import com.ifcar.app.util.BaseImageDownloader;
import com.ifcar.app.util.PicUtil;

import android.content.Context;
import android.util.AttributeSet;

/**
 * 根据width和设定的长宽比，比决定height
 * 
 * @author wjying
 */
public class FitImageView extends MyImageView {
    private float mRatio;

    private DownloadRunnable mDownloadRunnable;

    public FitImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public FitImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FitImageView(Context context) {
        super(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (mRatio > 0) {
            int measuredWidth = getMeasuredWidth();
            int measuredHeight = getMeasuredHeight();

            int targetMeasuredHeight = (int) (mRatio * measuredWidth);
            if (measuredHeight != targetMeasuredHeight) {
                setMeasuredDimension(measuredWidth, targetMeasuredHeight);
            }
        }
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (mDownloadRunnable != null) {
            mDownloadRunnable.run();
        }
    }

    /**
     * 设置长宽比
     * 
     * @param ratio
     */
    public void setRatio(float ratio) {
        if (mRatio != ratio) {
            mRatio = ratio;
            requestLayout();
        }
    }

    public void download(BaseImageDownloader downloader, String imgUrl) {
        mDownloadRunnable = null;
        if (getHeight() == 0) {
            mDownloadRunnable = new DownloadRunnable();
            mDownloadRunnable.mDownloader = downloader;
            mDownloadRunnable.mImgUrl = imgUrl;
        } else {
            downloadInternal(downloader, imgUrl);
        }
    }
    
    private void downloadInternal(BaseImageDownloader downloader, String imgUrl) {
        int width = getWidth() - getPaddingLeft() - getPaddingRight();
        int height = getHeight() - getPaddingTop() - getPaddingBottom();
        imgUrl = PicUtil.get3G_PhotoResize(imgUrl, width, height);
        downloader.setBitmapWandH(width, height, "Y");
        downloader.download(imgUrl, FitImageView.this);
    }

    private class DownloadRunnable implements Runnable {
        private BaseImageDownloader mDownloader;
        private String mImgUrl;

        @Override
        public void run() {
            mDownloadRunnable = null;
            downloadInternal(mDownloader, mImgUrl);
        }
    }
}
